import dayjs from 'dayjs'

const timestampFormat = (timestamp, type) => {
    // 兼容- 时间格式
    if (type) {
        return dayjs(timestamp).format(type);
    }

    try {
        timestamp = new Date(timestamp)
    } catch (err) {
        timestamp
    }
    let curTimestamp = parseInt(new Date().getTime()); //当前时间戳
    let timestampDiff =
        parseInt(curTimestamp / 1000) - parseInt(timestamp / 1000); // 参数时间戳与当前时间戳相差秒数

    let curDate = new Date(curTimestamp); // 当前时间日期对象
    let tmDate = new Date(timestamp); // 参数时间戳转换成的日期对象

    let Y = tmDate.getFullYear(),
        m = tmDate.getMonth() + 1,
        d = tmDate.getDate();

    if (timestampDiff < 60) {
        // 一分钟以内
        return "刚刚";
    } else if (timestampDiff < 3600) {
        // 一小时前之内
        return Math.floor(timestampDiff / 60) + "分钟前";
    } else if (
        curDate.getFullYear() == Y &&
        curDate.getMonth() + 1 == m &&
        curDate.getDate() == d
    ) {
        return "今天 " + dayjs(timestamp).format('HH:mm');
    } else {
        let newDate = new Date(curTimestamp - 86400000); // 参数中的时间戳加一天转换成的日期对象
        if (
            newDate.getFullYear() == Y &&
            newDate.getMonth() + 1 == m &&
            newDate.getDate() == d
        ) {
            return "昨天 " + dayjs(timestamp).format('HH:mm');
        } else if (curDate.getFullYear() == Y) {
            return dayjs(timestamp).format('MM月DD日 HH:mm');

        } else {
            return dayjs(timestamp).format('YYYY年MM月DD日');
        }
    }
};

export default function (input, type) {
    if (input) {
        return timestampFormat(input, type);
    } else {
        return "";
    }
}
